// ==UserScript==
// @name         IT之家博客增强
// @namespace    https://gitee.com/bluesword12350/web-script
// @version      1.0.0
// @description  IT之家博客已读变灰
// @author       李林峰
// @match        https://www.ithome.com/blog/
// @match        https://www.ithome.com/0/*
// @match        https://lapin.ithome.com/html/digi/*
// @icon         https://www.ithome.com/favicon.ico
// @updateURL    https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-ithome.js
// @downloadURL  https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-ithome.js
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(() => {
  'use strict';
  const setOpacity = '0.5'
  const maxBlogs = 3000;
  const GmBlogKey = "IT之家已读博客";

  let content = document.querySelector("#list > div.fl > ul")
  const blogURLPattern = new URLPattern("https://www.ithome.com/0/:folderId/:blogId.htm");
  const ggURLPattern = new URLPattern("https://lapin.ithome.com/html/digi/:blogId.htm");
  exec()
  function exec(){
    if (content) {
      new MutationObserver(construction).observe(content,{attributes: true, childList: true, subtree: true});
      setInterval(construction, 10000)
      construction()
    }
    {
      let blogURLPatternResult = blogURLPattern.exec(window.location.href)
      let ggURLPatternResult = ggURLPattern.exec(window.location.href)
      if (blogURLPatternResult) {
        let pathVariable = blogURLPatternResult.pathname.groups;
        let blogId = `${pathVariable.folderId}/${pathVariable.blogId}`
        saveBlogId(blogId);
      } else if (ggURLPatternResult){
        let pathVariable = ggURLPatternResult.pathname.groups;
        saveBlogId(pathVariable.blogId);
      }
    }
  }
  function saveBlogId(blogId) {
    let nowReadBlogIds = GM_getValue(GmBlogKey, []);
    if (!Array.isArray(nowReadBlogIds)) {
      GM_setValue(GmBlogKey, []);
    }
    if (!nowReadBlogIds.includes(blogId)) {
      nowReadBlogIds.unshift(blogId)
      GM_setValue(GmBlogKey, nowReadBlogIds);
      while (nowReadBlogIds.length > maxBlogs) {
        nowReadBlogIds.pop()
      }
    }
  }
  function construction(){
    let readBlogIds = GM_getValue(GmBlogKey, []);
    let blogs = content.getElementsByTagName("li")
    for (let blog of blogs) {
      let blogHref = blog.getElementsByClassName('title')[0].href
      let blogURLPatternResult = blogURLPattern.exec(blogHref)
      let ggURLPatternResult = ggURLPattern.exec(blogHref)
      if (blogURLPatternResult) {
        let pathVariable = blogURLPatternResult.pathname.groups;
        let blogId = `${pathVariable.folderId}/${pathVariable.blogId}`
        if (readBlogIds.includes(blogId)) {
          blog.style.opacity = setOpacity;
        }
      } else if (ggURLPatternResult) {
        let pathVariable = ggURLPatternResult.pathname.groups;
        if (readBlogIds.includes(pathVariable.blogId)) {
          blog.style.opacity = setOpacity;
        }
      }
    }
  }
})();
